#!/bin/sh
exec -a http_file_get python3 - "$@" << EOF
# python
import os
import sys
import argparse
from urllib.request import urlopen, Request
from urllib.error import URLError, HTTPError

def download_file(url, save_path, show_progress=True):
    """下载文件并保存到指定路径，返回操作结果"""
    try:
        with urlopen(Request(url), timeout=10) as response:
            if response.status != 200:
                return -1
            
            # 确保保存目录存在
            os.makedirs(os.path.dirname(save_path), exist_ok=True)

            file_size = int(response.headers.get('Content-Length', 0))
            # 根据文件大小自动选择块大小
            chunk_size = 1024 * 1024 if file_size > 100*1024*1024 else 64*1024
            
            downloaded = 0
            with open(save_path, 'wb') as f:
                while True:
                    chunk = response.read(chunk_size)
                    if not chunk:
                        break
                    downloaded += len(chunk)
                    if show_progress:
                        print(f"\r进度: {downloaded/(1024*1024):.2f}MB/{file_size/(1024*1024):.2f}MB", 
                              end='', flush=True)
                    f.write(chunk)
                    
                if show_progress:
                    print()  # 换行
        return 0
    except (URLError, HTTPError, OSError) as e:
        print(f"\n错误详情: {str(e)}")
        return -1

def main():
    parser = argparse.ArgumentParser(description='文件下载客户端')
    parser.add_argument('--host', default='localhost',
                       help='服务器地址（默认: localhost）')
    parser.add_argument('--port', type=int, default=8000,
                       help='服务器端口（默认: 8000）')
    parser.add_argument('--files', required=True, nargs='+',
                       help='要下载的服务端文件路径（支持多个文件，用空格分隔）')
    parser.add_argument('--output-dir', default=os.getcwd(),
                       help='文件保存目录（默认：当前目录）')
    parser.add_argument('--save-names', nargs='+',
                       help='自定义保存文件名（与--files一一对应）')
    parser.add_argument('--no-progress', action='store_true',
                       help='禁用进度显示')
    
    args = parser.parse_args()
    
    # 验证自定义文件名参数
    if args.save_names and len(args.save_names) != len(args.files):
        print("错误：--save-names参数数量必须与--files一致")
        sys.exit(-1)
    
    try:
        for i, file_path in enumerate(args.files):
            # 构建完整URL
            clean_file_path = file_path.lstrip('/')
            url = f'http://{args.host}:{args.port}/{clean_file_path}'
            
            # 确定保存文件名
            filename = args.save_names[i] if args.save_names else os.path.basename(clean_file_path)
            if not filename:
                print(f"错误：无法自动获取文件名 '{file_path}'，请使用--save-names指定")
                sys.exit(-1)
            
            save_path = os.path.join(args.output_dir, filename)
            
            # 开始下载
            print(f"[*] 正在下载({i+1}/{len(args.files)}): {url}")
            result = download_file(
                url, 
                save_path,
                show_progress=not args.no_progress
            )
            
            # 处理结果
            if result == 0:
                print(f"[+] 文件已保存: {os.path.abspath(save_path)}")
            else:
                print(f"[-] 文件下载失败: {url}")
                
    except KeyboardInterrupt:
        print("\n[!] 操作被用户中断")
        sys.exit(-1)

if __name__ == "__main__":
    main()

EOF